<?PHP
/*

OpenTrack API PHP Framework

This software is written to expedite clean and correct API calls to the DealerTrack Webservices
collectively known as "OpenTrack".  This framework is a simple introduction to how the API
works.  There are areas of incompleteness and oppourtunities for improvement.  If there are
features you need assistance with please contact jarrett@crownmotors.pro

Open Source Initiative OSI - The MIT License:Licensing

The MIT License

We have no copyright on this code. Infact this code is not worthy
of a copyright. However if it helps you in anyway
please send thanks to Jarrett Kuljis @ jarrett@crownmotors.pro

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

class Customer extends ArkonaDMS_Interop
{


	protected static $method 		= 	'Customer-API';

	public function customerLookup($customer_number) {
		
		if($customer_number == '') {
			parent::eLog("No customer number passed to application");
			return false;
		}
				
		$sp = '<CustomerLookup>
		';
		$sp .= parent::addDealerCode();
		$sp .= '<CustomerNumber>'.$customer_number.'</CustomerNumber> 
		</CustomerLookup>';
		
		return parent::execRequest($sp);
		
	}
	
	public function customerSearch($st) {
		
		if(!is_array($st)) {
			parent::eLog("Search request not passed in the form of an array... Integration Application Exiting");
			return false;
		}
		
		// ArkonaDMS_Interop::method		=	'CustomerSearch';
		// ArkonaDMS_Interop::method_vars	=	$st[0].'-'.$st[1].'-'.$st[2].'-'.$st[3];
		
		$sp	 =	'
				<CustomerSearch>';
					$sp.=	parent::addDealerCode();
					$sp	.=	'<SearchParms>';
					
					if($st[0] != '') { $sp.= '<LastName>'.$st[0].'</LastName>'; }
					if($st[1] != '') { $sp.= '<FirstName>'.$st[1].'</FirstName>'; }
					if($st[2] != '') { $sp.= '<Phone>'.$st[2].'</Phone>'; }
					if($st[3] != '') { $sp.= '<Email>'.$st[3].'</Email>'; }

		$sp	.=	' </SearchParms>
				</CustomerSearch>
				';

		parent::aLog("CustomerSearch : ".$sp);

		return parent::execRequest($sp);
	}	
	
	
	
	public function CustomerUpdate($ua, $ext_id) {
		
		if(!is_array($us) && !isset($ext_id)) {
			parent::eLog("Customer Update Method must have an array as primary argument");
			exit();
		}
	
		$sp = '<CustomerUpdate>';
		$sp .= parent::addDealerCode();
		$sp	.=	'	<Customer>';
		$sp	.=	'	<CustomerNumber>'.$ext_id.'</CustomerNumber>';
			//  Specify update fields
			foreach($ua as $k => $f) {
				$sp .= '<'.$k.'>'.$f.'</'.$k.'>';
			}
		$sp .=	'	</Customer>';
		$sp .= '</CustomerUpdate>';

		parent::aLog("Customer Update");
		return parent::execRequest($sp);
	}
	
	
	public function CustomerAdd($af) {
		
		/* required fields for add
		--------------------------
				TypeCode, C,I
				LastName (Company Name)
		*/
		global $mySf;
		
		if(!is_array($af) and !is_object($af)) {
			parent::eLog("CustomerAdd method requires array as primary argument");
			exit();
		} else {
			parent::aLog("CustomerAdd method begin");	
			if(is_array($af)) {
				$df = $af;
			}	
		}
		
		if($af->fields->LastName != '' ) 	{ $df['LastName'] = strval(c($af->fields->LastName)); }
		if($af->fields->FirstName!= '' ) 	{ $df['FirstName'] = strval(c($af->fields->FirstName)); } 
		if($af->fields->Phone!= '' ) 	 	{ $df['PhoneNumber'] = c($af->fields->Phone); } 
		if($af->fields->PersonEmail!= '' ) 	{ $df['Email'] = c($af->fields->PersonEmail); } 
		
		// Perform Customer Search as prerequisit of add
		if($df['LastName'] != '') 		{ $srch[0] = $df['LastName'];	}
		if($df['FirstName'] != '') 		{ $srch[1] = $df['FirstName'];	}
		if($df['PhoneNumber'] != '') 	{ $srch[2] = $df['PhoneNumber'];	}
		if($df['Email1'] != '') 		{ $srch[3] = $df['Email1'];	}
		
		if($af->fields->LastName != '' or $af->fields->Name != '') {
			$is_SF_record = true;		
			if($af->fields->IsPersonAccount == true) {
				// Map to customer account
				$ua['TypeCode']='I';
				$ua['LastName']=$af->fields->LastName;
				
				
				$ua['FirstName']=$af->fields->FirstName;
				($af->fields->Middle__c=='')?false:$ua['MiddleName']=$af->fields->Middle__c;
				($af->fields->Salutation=='')?false:$ua['Salutation']=$af->fields->Salutation;
				($af->fields->PersonMailingStreet=='')?false:$ua['Address1']=$af->fields->PersonMailingStreet; //45char
				// $ua['Address2']=$af->fields->;
				($af->fields->PersonMailingCity=='')?false:$ua['City']=$af->fields->PersonMailingCity;
				($af->fields->PersonMailingState=='')?false:$ua['StateCode']=$af->fields->PersonMailingState; 
				($af->fields->PersonMailingPostalCode=='')?false:$ua['ZipCode']=$af->fields->PersonMailingPostalCode;
				($af->fields->Phone=='')?false:$ua['PhoneNumber']=ereg_replace("[^0-9]", "", $af->fields->Phone);
				($af->fields->PersonMobilePhone=='')?false:$ua['CellPhone']=ereg_replace("[^0-9]", "", $af->fields->PersonMobilePhone);
				($af->fields->Fax=='')?false:$ua['FaxNumber']=ereg_replace("[^0-9]", "", $af->fields->Fax);
				($af->fields->Other_Phone__c=='')?false:$ua['OtherPhone']=ereg_replace("[^0-9]", "", $af->fields->Other_Phone__c);
				($af->fields->PersonBirthdate=='')?false:$ua['BirthDate']=date("Ymd", strtotime($af->fields->PersonBirthdate));
				($af->fields->Driver_s_Lic_Num__c=='')?false:$ua['DriversLicense']=$af->fields->Driver_s_Lic_Num__c;
				($af->fields->PersonEmail=='')?false:$ua['Email1']=$af->fields->PersonEmail;
				($af->fields->Alt_Email__c=='')?false:$ua['Email2']=$af->fields->Alt_Email__c;
				// $ua['CustomerPreferredName']='';
			}
			
			if($af->fields->IsPersonAccount == false) {
				$ua['TypeCode']='C';
				$ua['LastName']=$af->fields->Name;
				($af->fields->BillingStreet=='')?false:$ua['Address1']=$af->fields->BillingStreet;
				($af->fields->BillingCity=='')?false:$ua['City']=$af->fields->BillingCity;
				($af->fields->BillingState=='')?false:$ua['StateCode']=$af->fields->BillingState;
				($af->fields->BillingPostalCode=='')?false:$ua['ZipCode']=$af->fields->BillingPostalCode;
				// $ua['I_B_Flag__c']='B';
				// $ua['IsPersonAccount']=false;
				($af->fields->Phone=='')?false:$ua['BusinessPhone']=ereg_replace("[^0-9]", "", $af->fields->Phone);
				($af->fields->Fax=='')?false:$ua['FaxNumber']=ereg_replace("[^0-9]", "", $af->fields->Fax);
				($af->fields->Business_Email__c=='')?false:$ua['Email1']=$af->fields->Business_Email__c;
				($af->fields->Tax_Exempt_No__c=='')?false:$ua['TaxExmptNumber']=$af->fields->Tax_Exempt_No__c;
			}
			
		}
		
		$sdat	=	Customer::customerSearch($srch);
		
		if(strval($sdat->{'content'}->{'CustomerSearchResponse'}->{'Error'}->{'Code'}) != 'CS02') { 
			parent::eLog("CustomerSearch return results, unable to complete CustomerAdd method");
				
				// Validate All Customers found in search against this customer.
				foreach($sdat->{'content'}->{'CustomerSearchResponse'}->{'CustomerSearchResult'} as $cr) {
					$i_c++;
					parent::eLog("Matched - ".$cr->{'CustomerNumber'}." ".$cr->{'LastName'}."-S-{".$srch[0]."}, ".$cr->{'FirstName'}."-S-{".$srch[1]."} 
								H:".$cr->{'HomePhone'}."-S-{".$srch[2]."} 
								B:".$cr->{'BusinessPhone'}."-S-{".$srch[2]."}
								C:".$cr->{'CellPhone'}."-S-{".$srch[2]."}
								E1:".$cr->{'Email1'}."-S-{".$srch[3]."}
								E2:".$cr->{'Email2'}."-S-{".$srch[3]."}");		
									
				}
				
				if($i_c == 1) {
					// One result found conect records...
					if($cr->{'CustomerNumber'} != '' and $is_SF_record == true) {
						parent::aLog("CustomerAdd found a common account, updating external ID: ".$cr->{'CustomerNumber'}." -> ".$af->Id);
						if(!$mySf) { $mySf	=	getSFLogin(); }
						$dt_id_new	=	$cr->{'CustomerNumber'};
						$cO = array();
						$cO['DealertrackID__c']=$cr->{'CustomerNumber'};
						$c_Object 				= 	new SObject();
						$c_Object->type			=	'Account';
						$c_Object->Id			=	$af->Id;
						$c_Object->fields 		= 	$cO;
						$CreateResponse			=	'';
						try {
							$CreateResponse = $mySf->update(array($c_Object));
							parent::aLog($CreateResponse->message);
							if(!$CreateResponse->success) {
								parent::eLog($CreateResponse->errors->message);
								parent::eLog(print_r($c_Object));
							}
						} catch(Exception $e) {
							parent::eLog("Error upserting Customer");
							parent::eLog($e->faultstring);
							parent::eLog(print_r($c_Object));
						}						
					}
				}
				
			return false;
		} else {
			$data_token = strval($sdat->{'content'}->{'CustomerSearchResponse'}->{'DataToken'});
			parent::aLog("CustomerAdd - search for dupes returned no results, DataToken = ".$data_token);	
		}	
		
		
		if(!$data_token) {
			parent::eLog("CustomerAdd method requires data_token for payload insert");
			return false;
		}
		
		$sp  = '<CustomerAdd>';
		$sp .=  parent::addDealerCode();
		$sp .= '<Customer>';
			
			// Create fields for custom insert / add
			foreach($ua as $k => $f) {
				$sp .= '<'.$k.'>'.$f.'</'.$k.'>';
			}		
		$sp .= '<DataToken>'.$data_token.'</DataToken>';		
		$sp .= '</Customer>';
		$sp .= '</CustomerAdd>';
		
		parent::aLog("Customer Add Method payload sending now...");
		
		$rtn_sts	= parent::execRequest($sp);		
		
		if($rtn_sts->{'content'}->{'CustomerAddResponse'}->{'Success'}->{'CustomerNumber'} != '') {
			parent::aLog("CustomerAdd created DMSId: ".$rtn_sts->{'content'}->{'CustomerAddResponse'}->{'Success'}->{'CustomerNumber'});
			return rtn_sts;
		} else {
			return false;
		}
		
	}
	
	
	public function CustomerList($params=array()) {
	
		/*
		Array of search params for list
		
		  0 <IncludeCompanies>Y</IncludeCompanies>
		  1 <ZipCode>84095</ZipCode>
		  2 <ExcludeBlankAddress>Y</ExcludeBlankAddress>
		  3 <ExcludeBlankPhone>Y</ExcludeBlankPhone>
		  4 <ExcludeBlankEmail>Y</ExcludeBlankEmail>

		*/
	
		$sp  = '<CustomerList>';
		$sp .=  parent::adddealerCode();
		$sp .= '<ListParms>';
		if(is_array($params) and count($params) > 0) {	
			
			if($params[0] != '') {	$sp.= '<IncludeCompanies>'.trim($params[0]).'</IncludeCompanies>'; } 
			if($params[1] != '') {	$sp.= '<ZipCode>'.trim($params[1]).'</ZipCode>'; }
			if($params[2] != '') {	$sp.= '<ExcludeBlankAddress>'.trim($params[2]).'</ExcludeBlankAddress>'; }
			if($params[3] != '') {	$sp.= '<ExcludeBlankPhone>'.trim($params[3]).'</ExcludeBlankPhone>'; }
			if($params[4] != '') {	$sp.= '<ExcludeBlankEmail>'.trim($params[4]).'</ExcludeBlankEmail>'; }
			
		}				
		$sp .= '</ListParms>';
		$sp .= '</CustomerList>';
	
		parent::aLog("Customer List Method");
		return parent::execRequest($sp);
	}
	
}
?>